/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.controller;

import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.purpose.bean.ContributoryPlanBean;
import com.koron.purpose.service.api.ContributoryPlanService;
import com.koron.purpose.utils.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "contributoryPlan", description = "投入计划")
@RestController
@RequestMapping("/contributoryPlan")
public class ContributoryPlanController {
    private final static  Logger logger = LoggerFactory.getLogger(ContributoryPlanController.class);

    @Autowired
    private ContributoryPlanService contributoryPlanService;

    @ApiOperation("列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "year", value = "年份",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "manager", value = "单位code",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "statusFlag", value = "状态标记(1-审批通过 2-草稿)",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页",  dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数",  dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词",  paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/queryForList.htm", method = RequestMethod.GET)
    public MessageBean queryForList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String corpCode, @ApiIgnore Integer year, @ApiIgnore String manager, @ApiIgnore String statusFlag,
                                    @ApiIgnore Integer page, @ApiIgnore Integer pageSize, @ApiIgnore String keyword) {
        if (null == user) {
            MessageBean msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        return contributoryPlanService.queryForList(corpCode, year, manager, statusFlag, page, pageSize,keyword);
    }

    @ApiOperation("根据ID查询投入计划")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/queryById.htm", method = RequestMethod.GET)
    public MessageBean queryById(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String id) {
        if (null == user) {
            MessageBean msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        return contributoryPlanService.queryById(id);
    }

    @ApiOperation("根据ID删除投入计划")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/deleteById.htm", method = RequestMethod.POST)
    @Log(title = "根据ID删除投入计划", businessModule = "安全投入", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean deleteById(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String id) {
        if (null == user) {
            MessageBean msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        return contributoryPlanService.deleteById(id);
    }

    @ApiOperation("新增投入计划")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobsTasksId", value = "工作任务ID",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpName", value = "水司名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "year", value = "年份", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "manager", value = "单位code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "managerName", value = "单位名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "serialNumber", value = "编号", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "statusFlag", value = "状态标记(只能传 0-审批中 2-草稿)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "details", value = "投入计划(JSON格式字符串，如：" +
                    "[{'contributoryProject':'投入项目code','contributoryProjectName':'投入项目名称'," +
                    "'contributoryDetail':'投入明细','time':'计划投入时间'," +
                    "'planMoney':'计划投入金额','personCharge':'责任人'," +
                    "'personChargeName':'责任人名称','remark':'备注'}])",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "personCodes", value = "审批人code数组", required = true, paramType = "query", dataType = "String"),
    })
    @RequestMapping(value = "/insert.htm", method = RequestMethod.POST)
    @Log(title = "新增投入计划", businessModule = "安全投入", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean insert(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                              @ApiIgnore ContributoryPlanBean bean, @ApiIgnore String jobsTasksId,
                              @ApiIgnore String details, @RequestParam(value = "files", required = false) MultipartFile[] files,
                              @ApiIgnore String personCodes) {
        if (null == user) {
            MessageBean msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        return contributoryPlanService.insert(user, bean, details, files, jobsTasksId, personCodes);
    }

    @ApiOperation("修改投入计划(只能修改2-草稿)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobsTasksId", value = "工作任务ID",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "year", value = "年份", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "manager", value = "单位code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "managerName", value = "单位名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "serialNumber", value = "编号", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "statusFlag", value = "状态标记(只能传 0-审批中 2-草稿)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "details", value = "投入计划(JSON格式字符串，如：" +
                    "[{'id':'id','contributoryPlanId':'投入计划id'," +
                    "'contributoryProject':'投入项目code','contributoryProjectName':'投入项目名称'," +
                    "'contributoryDetail':'投入明细','time':'计划投入时间'," +
                    "'planMoney':'计划投入金额','personCharge':'责任人'," +
                    "'personChargeName':'责任人名称','remark':'备注'}])",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "accessorys", value = "附件(参数格式为JSON字符串，" +
                    "如( [{'filename':'xxx','fileUrl':'xxx'},{'filename':'xxx','fileUrl':'xxx'}] ))",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "personCodes", value = "审批人code数组", required = true, paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/update.htm", method = RequestMethod.POST)
    @Log(title = "修改投入计划", businessModule = "安全投入", businessManipulation = BusinessManipulation.UPDATE)
    public MessageBean update(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                              @ApiIgnore ContributoryPlanBean bean, @ApiIgnore String statusFlag,
                              @ApiIgnore String details, @ApiIgnore String accessorys,
                              @RequestParam(value = "files", required = false) MultipartFile[] files,
                              @ApiIgnore String jobsTasksId, @ApiIgnore String personCodes) {
        if (null == user) {
            MessageBean msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        return contributoryPlanService.update(user, bean, statusFlag, details, accessorys, files, jobsTasksId, personCodes);
    }

    @ApiOperation("编号验重")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "serialNumber", value = "编号", required = true, paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/changeSerialNumber.htm", method = RequestMethod.GET)
    public MessageBean changeSerialNumber(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String id, @ApiIgnore String serialNumber) {
        if (null == user) {
            MessageBean msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        return contributoryPlanService.changeSerialNumber(id, serialNumber);
    }

    @ApiOperation("流程中的业务数据")
    @ApiImplicitParam(name = "ids", value = "流程关联的业务ids,如: ['id1','id2'] ", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getProcessData.htm", method = {RequestMethod.GET})
    public MessageBean<?> getProcessData(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String ids) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        return contributoryPlanService.getProcessData(ids);
    }

    @ApiOperation("导出投入计划")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "year", value = "年份",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "manager", value = "单位code",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "statusFlag", value = "状态标记(1-审批通过 2-草稿)",  paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/exportContPlan.htm", method = RequestMethod.GET)
    @Log(title = "导出投入计划", businessModule = "安全投入", businessManipulation = BusinessManipulation.EXPORT)
    public HttpEntity<?> exportContPlan(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String corpCode, @ApiIgnore String year,
                                        @ApiIgnore String manager, @ApiIgnore String statusFlag) {
        if (null == user) {
            return null;
        }
        List<Map> list = contributoryPlanService.queryExportForList(corpCode, year, manager, statusFlag);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File file = new File("static/excel/ContributoryPlanExport.xlsx");
        try (
                InputStream inputStream = getClass().getClassLoader().getResourceAsStream("static/excel/ContributoryPlanExport.xlsx");
        ) {
            FileUtils.copyInputStreamToFile(inputStream, file);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("投入计划", file, "ContributoryPlanExport.btl", map);
    }
}
